# -*- coding:utf-8 -*-
from datakeeper.models import *
from weblib.django.user import *
from fengge.models import *
from .workers import *

tags_dict = {}
#for ptype in WrasProjectType.objects.all():
 #   tags = [tag.name for tag in ptype.dataset_tags.all()]
#    tags_dict[ptype.name] = tags

#@receiver(sig_project_item_created, sender=WrasProjectItem, dispatch_uid='GET_PITEM_BRIEFS_DUID')
def get_briefs_for_pitem(sender, instance, **kwargs):
    # TODO: 根据project类型或pitem的info.info定选用什么样的数据集
    # tags_dict = {
    #     'wind': ['wind'],
    #     'default': ['wind'],
    #     'solar': ['solar'],
    #     'met': ['meteorology']
    # }

    user = clean_user(instance.creator_name)
    if instance.item_type == 'Point':
        # data_briefs = data_keeper.get_briefs(target={'type':'point_item', 'item':instance})
        projtype = instance.project.ptype.name
        data_briefs = data_keeper.lookup({
            'type': 'point',
            'lon': instance.sub_item.lon,
            'lat': instance.sub_item.lat,
            'dataset_tags': tags_dict[projtype]
        }, user=user)
    # TODO more types
    elif instance.item_type in ['Rect', 'MultiPolygon']:
        projtype = instance.project.ptype.name
        data_briefs = data_keeper.lookup({
            'type': 'rect',
            'lon1': instance.sub_item.lon1,
            'lon2': instance.sub_item.lon2,
            'lat1': instance.sub_item.lat1,
            'lat2': instance.sub_item.lat2,
            'dataset_tags': tags_dict[projtype]
        }, user=user)
    else:
        data_briefs = []
   # logger.debug("Got Product Info:\n" + unicode(data_briefs))
    instance.data_briefs = data_briefs
    instance.save()

@receiver(post_save, sender=AUTH_USER_MODEL, dispatch_uid='CREATE_USER_DATA_SETTING_DUID')
def create_user_data_setting(sender, **kwargs):
    user = kwargs['instance']
    created = kwargs['created']
    if created:
        user_data_setting = UserDataSetting(user=user)
        user_data_setting.save()


@receiver(post_save, sender=AUTH_USER_MODEL, dispatch_uid='CREATE_USER_ACCOUNT_DUID')
def create_user_account(sender, **kwargs):
    user = kwargs['instance']
    created = kwargs['created']
    if created:
        pass
     #   for acc_type in AccountType.objects.all():
     #       account_name = u'%s:%s' % (user.username, acc_type.name)
     #      acc, created = Account.objects.get_or_create(name=account_name, defaults={
     #           "user": user,
     #           "type": acc_type,
      #          "priority": acc_type.priority,
      #      })
      ##      if created:
      #          print account_name


@receiver(post_save, sender=AUTH_USER_MODEL, dispatch_uid='CREATE_USER_PROFILE_DUID')
def create_user_profile(sender, **kwargs):
    user = kwargs['instance']
    created = kwargs['created']
    if created:
        pass
      #  uinfo = UserProfile(user=user)
      #  uinfo.save()

